package com.test.Protection;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.test.license.License;
import com.test.license.LicenseReader;
import com.test.storage.FileSecretStorage;
import com.test.storage.SecretStorage;


import java.util.Date;

/**
 * @author: zouren
 * @date: 2022/3/14
 * @description: 支撑
 */
public class A {
    private LicenseReader licenseReader;
    private SecretStorage secretStorage;
    private static boolean isLoad = true;
    private static Date loadDate = DateUtil.date();

    public A() {
        initLicenseReader();
        initSecretStorage();
    }

    private void initLicenseReader() {
        this.licenseReader = new LicenseReader();
        //TODO 设置license 解秘私钥
        this.licenseReader.setDecryptPriKey("MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIJhie1i661ptdOShCAhsNgG0lLF55TPSgoDzzAo+RweGMznV6APHisOohfXLbhXJTY5WV6gUL8p/srKGwzVMu68Z2ihFnEM2DaWqBMukqdkCVEI/Qcyn3JmzvyUrBhCAiA93UTC+2rUwLhMNm5TQmiY36Y4RPYoggeVmUXXWsFlAgMBAAECgYBlTC8DVsXRF76DQOSSqlphnPswAD7q6RqXKVqCCnNxGxkdqef0nYpM3bOmXjJRdLOeq3P6Bwh1XcVt/RSDJenJYSsuz368VKYM9kwYugcJ4txW3AVbMbMYrdJ5vlOK2ZfPtnm3kbbEtsSwQlpzvCQMhE5aKgUE/7GF4pCei+7eQQJBAMmAXBLt95yxdcMuc9tIPOJCIGA+5Z8bd0jhe8uv3Xe6a91aNXdrJmbC6bSlsboyVWFIfnWtk0YuA3364QcaqF0CQQClpOo2d6a9nbsAlAXMlHRKlTyAqS3/1zpAAnsUZOkLUzYhVjuNQPAwH6iG9dprT9fO47HMbfuunuuv+bDrfkypAkBwkWjemlpuCyWCuHy40A5TSCXWHs0gqbNl37HNBJ5wuJBxxGeCIzX8yn7NEJPNNTlFc75R93oDBsmko3b7BQVxAkEAjKhMpnHWKl/dIvGPNxi843R0iwCeagj2ktJId5n09sPzTD2wlhMVopfPgMMWdVe4dxuMqH6gYLjchHMwE9kM+QJBAK7YqhIcDlYJDlh7dqkdznHdhYou3mj6pp9RZq+gof1XsWu8J+9ggv0NdsjU/XaoL2WUF0h/E8poFFSs0jdq86I=");
    }

    private void initSecretStorage() {
        this.secretStorage = new FileSecretStorage();
        //TODO 加密
        secretStorage.setSkipEncryption(true);

    }

    public boolean checkLicense(boolean refresh) {
        License license = this.licenseReader.getLicense(refresh);
        if(license==null){
            Runtime.getRuntime().exit(1);;
            return false;
        }
        boolean re = checkStorage(license);
        if (isLoad) {
            isLoad = false;
        } else if (DateUtil.between(loadDate, DateUtil.date(), DateUnit.DAY) > 1) {
            isLoad = true;
        }
        if (re) {
            long curTime = System.currentTimeMillis();
            long licenseTime = license.getInstallDate().getTime();
            long expTime = license.getExpiresDate().getTime();
            if (curTime < licenseTime || curTime > expTime) {
                re = false;
            }
        }
        Pc.getInstance().setState(re?1:0);
        return re;
    }

    private boolean checkStorage(License license) {
        long curTime = System.currentTimeMillis();
        long licenseTime = license.getInstallDate().getTime();
        Long expTime = license.getExpiresDate().getTime();

        //上次校验时间
        Long perCheckTime = getLongStorageProperty(SecretStorage.KEY_PREVIOUSSHUTDOWNDATE, null, isLoad);
        if (perCheckTime == null || perCheckTime < curTime) {
            saveStorageProperty(SecretStorage.KEY_PREVIOUSSHUTDOWNDATE, curTime + "");
        }
        //过期时间
        Long previousExpirationDate = getLongStorageProperty(SecretStorage.KEY_PREVIOUSEXPIRATIONDATE, null, isLoad);
        if (previousExpirationDate == null || previousExpirationDate.longValue() != expTime.longValue()) {
            saveStorageProperty(SecretStorage.KEY_PREVIOUSEXPIRATIONDATE, expTime + "");
        }

        //过期状态
//        Boolean alreadyExpired = getBooleanStorageProperty(SecretStorage.KEY_ALREADYEXPIRED, null, isLoad);
//        if (alreadyExpired == null || alreadyExpired.equals(Boolean.TRUE)) {
        Boolean flag = curTime >= licenseTime && curTime <= expTime;
        saveStorageProperty(SecretStorage.KEY_ALREADYEXPIRED, flag.toString());
//        }

        //license 状态可用 与 上次校验时间对应

        perCheckTime = getLongStorageProperty(SecretStorage.KEY_PREVIOUSSHUTDOWNDATE, null, false);
        Boolean checkTimeFlag = curTime >= perCheckTime;
        saveStorageProperty(SecretStorage.KEY_LICENSEACCEPTED, checkTimeFlag.toString());
        System.out.println("上次校验时间perCheckTime="+ DateUtil.date(perCheckTime));
        System.out.println("curTime="+ DateUtil.date(curTime));
        System.out.println("安装时间licenseTime="+ DateUtil.date(licenseTime));
        System.out.println("过期时间expTime="+ DateUtil.date(expTime));
        System.out.println("isLoad="+isLoad);

        return getBooleanStorageProperty(SecretStorage.KEY_ALREADYEXPIRED, Boolean.FALSE.toString(), false)
                && getBooleanStorageProperty(SecretStorage.KEY_LICENSEACCEPTED, Boolean.FALSE.toString(), false);
    }

    public String loadStorageProperty(String propertyName, String defaultValue, boolean forceLoad) {
        if (forceLoad) {
            this.secretStorage.load();
        }
        return this.secretStorage.getProperty(propertyName, defaultValue);
    }

    public void saveStorageProperty(String propertyName, String value) {
        secretStorage.setProperty(propertyName, value);
        secretStorage.save();
    }

    public Long getLongStorageProperty(String propertyName, String defaultValue, boolean forceLoad) {
        Long re = null;
        String l = loadStorageProperty(propertyName, defaultValue, forceLoad);
        if (l != null) {
            re = Long.parseLong(l);
        }
        return re;
    }

    public Date getDateStorageProperty(String propertyName, String defaultValue, boolean forceLoad) {
        Date re = null;
        String l = loadStorageProperty(propertyName, defaultValue, forceLoad);
        if (l != null) {
            Date date = DateUtil.date(Long.parseLong(l));
            return DateUtil.endOfDay(date);
        }
        return re;
    }

    public Boolean getBooleanStorageProperty(String propertyName, String defaultValue, boolean forceLoad) {
        Boolean re = null;
        String l = loadStorageProperty(propertyName, defaultValue, forceLoad);
        if (l != null) {
            re = Boolean.parseBoolean(l);
        }
        return re;
    }
}
